<template>
  <div class="p-2">
    <a-form class="smart-query-form">
      <a-row class="smart-query-form-row">
        <a-form-item label="流程标识" class="smart-query-form-item">
          <a-input v-model:value="queryParams.processKey" placeholder="请输入流程标识" style="width: 300px" />
        </a-form-item>
        <a-form-item label="流程名称" class="smart-query-form-item">
          <a-input v-model:value="queryParams.processName" placeholder="请输入流程名称" style="width: 300px" />
        </a-form-item>
        <a-form-item label="流程分类" class="smart-query-form-item">
          <a-select v-model:value="queryParams.category" placeholder="流程分类" style="width: 300px">
            <a-select-option v-for="item in categoryOptions" :key="item.categoryId" :value="item.code">
              {{ item.categoryName }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="提交时间" class="smart-query-form-item">
          <a-range-picker v-model:value="dateRange" style="width: 300px" />
        </a-form-item>

        <a-form-item class="smart-query-form-item smart-margin-left10">
          <a-button-group>
            <a-button type="primary" @click="handleQuery">
              <template #icon><SearchOutlined /></template>
              查询
            </a-button>
            <a-button @click="resetQuery">
              <template #icon><ReloadOutlined /></template>
              重置
            </a-button>
          </a-button-group>
        </a-form-item>
      </a-row>
    </a-form>

    <a-card size="small" :bordered="false">
      <a-row class="smart-table-btn-block">
        <div class="smart-table-operate-block">
          <a-button type="primary" :disabled="multiple" @click="handleDelete()">
            <template #icon><DeleteOutlined /></template>
            删除
          </a-button>
          <a-button type="primary" @click="handleExport()">
            <template #icon><FileExcelOutlined /></template>
            导出
          </a-button>
        </div>
      </a-row>

      <a-table
        :loading="loading"
        :dataSource="ownProcessList"
        :columns="columns"
        :pagination="false"
        :rowSelection="{ onChange: handleSelectionChange }"
        bordered
        :scroll="{ x: 1500 }"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.dataIndex === 'procDefVersion'">
            <a-tag>v{{ record.procDefVersion }}</a-tag>
          </template>
          <template v-if="column.dataIndex === 'processStatus'">
            <!-- <dict-tag :options="wf_process_status" :value="record.processStatus" /> -->
          </template>
          <template v-if="column.dataIndex === 'action'">
            <div class="smart-table-operate">
              <a-button type="link" @click="handleDetails(record)">详情</a-button>
              <a-button type="link" @click="handleStop(record)">取消</a-button>
              <a-button type="link" @click="handleAgain(record)">再次发起</a-button>
              <a-button type="link" @click="handleDelete(record)">删除</a-button>
            </div>
          </template>
        </template>
      </a-table>

      <div class="smart-query-table-page">
        <a-pagination
          v-model:current="queryParams.pageNum"
          v-model:pageSize="queryParams.pageSize"
          :total="total"
          :show-total="(total) => `共${total}条`"
          @change="getList"
        />
      </div>
    </a-card>
  </div>
</template>

<script setup name="Own">
  import { processApi } from '/@/api/workflow/work';
  import { categoryApi } from '/@/api/workflow/category';

  import { message, Modal } from 'ant-design-vue';

  const router = useRouter();
  const { proxy } = getCurrentInstance();
  // const { wf_process_status } = toRefs(proxy?.useDict('wf_process_status'));

  const categoryOptions = ref([]);

  const ownProcessList = ref([]);
  const loading = ref(true);
  const showSearch = ref(true);
  const ids = ref([]);
  const single = ref(true);
  const multiple = ref(true);
  const total = ref(0);
  const dateRange = ref(['', '']);

  const queryFormRef = ref();

  const queryParams = ref({
    pageNum: 1,
    pageSize: 10,
    processKey: '',
    processName: '',
    category: '',
  });

  /** 查询流程分类列表 */
  const getCategoryList = async () => {
    const res = await categoryApi.listAllCategory();
    categoryOptions.value = res.data;
  };

  /** 查询我的流程列表 */
  const getList = async () => {
    loading.value = true;
    const { data } = await processApi.listOwnProcess(queryParams.value);
    ownProcessList.value = data.list;
    total.value = data.total;
    loading.value = false;
  };

  /** 搜索按钮操作 */
  const handleQuery = () => {
    queryParams.value.pageNum = 1;
    getList();
  };

  /** 重置按钮操作 */
  const resetQuery = () => {
    queryFormRef.value.resetFields();
    handleQuery();
  };

  /** 多选框选中数据 */
  const handleSelectionChange = (selection) => {
    ids.value = selection.map((item) => item.procInsId);
    single.value = selection.length != 1;
    multiple.value = !selection.length;
  };

  /** 流程详情 */
  const handleDetails = (row) => {
    router.push({
      path: '/work/detail/' + row.procInsId,
      query: {
        processed: false,
      },
    });
  };

  /** 取消流程申请 */
  const handleStop = async (row) => {
    await processApi.stopProcess({ procInsId: row.procInsId });
    message.success('操作成功');
    getList();
  };

  /** 再次发起流程 */
  const handleAgain = (row) => {
    router.push({
      path: '/workflow/start/' + row.deployId,
      query: {
        definitionId: row.procDefId,
        procInsId: row.procInsId,
      },
    });
  };

  /** 删除按钮操作 */
  const handleDelete = async (row) => {
    const procInsIds = row?.procInsId || ids.value;
    Modal.confirm({
      title: '确认删除',
      content: `是否确认删除流程定义编号为"${procInsIds}"的数据项?`,
      async onOk() {
        await processApi.delProcess(procInsIds);
        getList();
        message.success('删除成功');
      },
    });
  };

  /** 导出按钮操作 */
  const handleExport = () => {
    proxy?.download(
      'workflow/process/ownExport',
      {
        ...queryParams.value,
      },
      `own_process_${new Date().getTime()}.xlsx`
    );
  };

  const categoryFormat = (row) => {
    return categoryOptions.value.find((k) => k.code === row.category)?.categoryName ?? '';
  };

  const columns = [
    {
      title: '流程编号',
      dataIndex: 'procInsId',
    },
    {
      title: '流程名称',
      dataIndex: 'procDefName',
    },
    {
      title: '流程类别',
      dataIndex: 'category',
      customRender: ({ text }) => categoryFormat({ category: text }),
    },
    {
      title: '流程版本',
      dataIndex: 'procDefVersion',
      
      align: 'center',
    },
    {
      title: '当前节点',
      dataIndex: 'taskName',
      align: 'center',
    },
    {
      title: '提交时间',
      dataIndex: 'createTime',
    
      align: 'center',
    },
    {
      title: '流程状态',
      dataIndex: 'processStatus',
      
      align: 'center',
      customRender: ({ text }) => {
        return text && text.length > 0 ? text.map((e) => e.valueName).join(',') : '';
      },
    },
    {
      title: '耗时',
      dataIndex: 'duration',
      
      align: 'center',
    },
    {
      title: '操作',
      dataIndex: 'action',
      width: 220,
      align: 'center',
      fixed: 'right',
    },
  ];

  const isMounted = ref(false);
  onMounted(async () => {
    await getCategoryList();
    await getList();
    isMounted.value = true;
  });

  onActivated(() => {
    if (isMounted.value) {
      getList();
    }
  });
</script>

<style scoped>
  .smart-query-form {
    margin-bottom: 16px;
  }

  .smart-table-operate {
    display: flex;
    justify-content: center;
    gap: 8px;
  }
</style>
